var intervalTime  = null; //页面定时

var hash = getHash();
if(hash != '') {
    if(hash == 'systemInfo') {
        $('.detail-header h1 .nav-title').html('系统信息');
    } else if(hash == 'systemStatus'){
        $('.detail-header h1 .nav-title').html('本机状态');
    } else if(hash == 'zfzStatus') {
        $('.detail-header h1 .nav-title').html('直放站状态');
    } else if(hash == 'network') {
        $('.detail-header h1 .nav-title').html('网络配置');
    } else if(hash == 'update'){
        $('.detail-header h1 .nav-title').html('升级更新');
    }
    $('#myTab a[href="#'+hash+'"]').tab('show');
} else {
    $('.detail-header h1 .nav-title').html('系统信息');
    $('#myTab a[href="#systemInfo"]').tab('show');
}

/*---------------------modal模态框 start---------------------------*/
$('#myModal').on('show.bs.modal', function(event) {
    var button = $(event.relatedTarget);
    var recipient = button.data('whatever');
    var $id = button.attr('data-key');
    var $value = button.attr('data-value');
    var modal = $(this);
    if ($id == 'ServerPort' || $id == 'HeartTimeUP' || $id == 'HeartTimeDN' || $id == 'UPDataTTI') {
        modal.find('.modal-body .setInput').attr({
            'min': 0,
            'max': 65535,
            'data-content': '数值范围为0~65535'
        });
    } else if ($id == 'FMFreq') {
        modal.find('.modal-body .setInput').attr({
            'min': 70.00,
            'max': 108.00,
            'data-content': '70.00MHz～108.00Mhz,小数点后2位'
        });
    } else if ($id == 'AmpTrackPower' || $id == 'AmpPowerThreshold') {
        modal.find('.modal-body .setInput').attr({
            'min': 0,
            'max': 30.0,
            'data-content': '0~30.0W,小数点后1位'
        });
    } else if ($id == 'AmpVSWRThreshold') {
        modal.find('.modal-body .setInput').attr({
            'min': 0,
            'max': 25.5,
            'data-content': '0~25.5,小数点后1位'
        });
    } else if ($id == 'LightRFAttrSet') {
        modal.find('.modal-body .setInput').attr({
            'min': 0,
            'max': 31,
            'data-content': '数值范围0~31db'
        });
    } else if ($id == 'DASet' || $id == 'AmpDACThreshold') {
        modal.find('.modal-body .setInput').attr({
            'min': 0,
            'max': 4095,
            'data-content': '数值范围0~4095'
        });
    } else if ($id == 'AmpTMPThreshold') {
        modal.find('.modal-body .setInput').attr({
            'min': 0,
            'max': 100,
            'data-content': '数值范围0~100℃'
        });
    } else {
        modal.find('.modal-body .setInput').removeAttr('min').removeAttr('max').removeAttr('data-content');
    }

    modal.find('.modal-title').text(recipient);
    modal.find('.modal-body .control-label').text(recipient);
    modal.find('.modal-body .setInput').attr('data-key', $id); //设置input的id
    if ($value != '未知') {
        modal.find('.modal-body .setInput').val($value);
    }
});

//功放控制模式
$('#AmpControlModal').on('show.bs.modal', function(event) {
    var button = $(event.relatedTarget);
    var recipient = button.data('whatever');
    var modal = $(this);
    var $value = button.attr('data-value');
    if ($value == 0) {
        $("input[name=AmpControlMode][value=0]").prop('checked', true);
    } else if ($value == 1) {
        $("input[name=AmpControlMode][value=1]").prop('checked', true);
    }
});

//是否动态获取
$('#DHCPModal').on('show.bs.modal', function(event) {
    var button = $(event.relatedTarget);
    var recipient = button.data('whatever');
    var modal = $(this);
    var $value = button.attr('data-value');
    if ($value == 0) {
        $("input[name=IsDHCPOption][value=0]").prop('checked', true);
    } else if ($value == 1) {
        $("input[name=IsDHCPOption][value=1]").prop('checked', true);
    }
});


/*---------------------modal模态框 end---------------------------*/

/*--------------------获取直放站数据start--------------------------*/
getOHOPTData();
getNetWorkData();
//定时查询
setInterval(function() {
    getOHOPTData();
    getNetWorkData();
},500);

/**
 * 获取直放站设备的实时参数----系统信息、本机信息、直放站状态
 * @return {[type]} [description]
 */
function getOHOPTData() {
    $.ajax({
        url: geturl('OHOPT_CGI.cgi/OHOPTDATA'),
        type: 'GET',
        beforeSend: function(xhr) {
            // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
            xhr.setRequestHeader("Content-Type", "application/json")
        },
        success: function(res) {
            if (res.success == "true") {
                var data = res.data;
                //系统信息
                $("#PCBVersion").html(data.PCBVersion);
                $("#BootVersion").html(data.BootVersion);
                $("#BootVerDate").html(data.BootVerDate);
                $("#BootVerTime").html(data.BootVerTime);
                $("#AppVersion").html(data.AppVersion);
                $("#AppVerDate").html(data.AppVerDate);
                $("#AppVerTime").html(data.AppVerTime);
                $("#CARDTag").html(data.CARDTag);
                $("#DevSnNum").html(data.DevSnNum);
                $("#MCUTemp").html(data.MCUTemp + '℃');
                $("#FLASHSta").html(getStatus(data.FLASHSta));
                $("#ARMTag").html(data.ARMTag);
                $("#ARMDevVersion").html(data.ARMDevVersion);

                //本机状态
                $("#ServerIP").html(data.ServerIP);
                $("#setServerIp").attr('data-value', data.ServerIP); //设置模态框

                $("#ServerPort").html(data.ServerPort);
                $("#setServerPort").attr('data-value', data.ServerPort); //设置模态框

                $("#HeartTimeUP").html(data.HeartTimeUP);
                $("#setHeartTimeUp").attr('data-value', data.HeartTimeUP); //设置模态框

                $("#UPDataTTI").html(data.UPDataTTI);
                $("#setUpDataTTI").attr('data-value', data.UPDataTTI); //设置模态框

                $("#HeartTimeDN").html(data.HeartTimeDN);
                $("#setHeartTimeDN").attr('data-value', data.HeartTimeDN); //设置模态框


                $("#FMFreq").html(data.FMFreq + 'MHz');
                $("#setFMFreq").attr("data-value", data.FMFreq); //设置模态框

                $("#THSta").html(getStatus(data.THSta));
                $("#Temp").html(data.Temp + '℃');
                $("#Humi").html(data.Humi + '%RH');
                $("#FMSta").html(getStatus(data.FMSta));
                $("#FMRSSI").html(data.FMRSSI + 'dbuv');
                $("#FMSNR").html(data.FMSNR + 'db');
                $("#MasterVol").html(data.MasterVol + 'V');
                $("#MasterCur").html(data.MasterCur + 'A');
                $("#BackupVol").html(data.BackupVol + 'V');
                $("#BackupCur").html(data.BackupCur + 'A');

                $("#ComSta").html(getStatus(data.ComSta));
                $("#TXCNT").html(data.TXCNT);
                $("#RXCNT").html(data.RXCNT);
                $("#DataTime").html(res.DataTime);

                //直放站状态
                $("#RFSwitch").html(getOpen(data.RFSwitch));
                if (data.RFSwitch == 1) { //开机状态
                    $("#setSwitch").removeClass('switch--close').addClass('switch--open');
                } else if (data.RFSwitch == 0) { //关机状态
                    $("#setSwitch").removeClass('switch--open').addClass('switch--close');
                }
                //输出功率设置
                $("#AmpTrackPower").html(data.AmpTrackPower + 'W');
                $("#setAmpTrackPower").attr('data-value', data.AmpTrackPower); //设置模态框
                //光模块衰减设置值
                $("#LightRFAttrSet").html(data.LightRFAttrSet + 'db');
                $("#setLightRFAttrSet").attr('data-value', data.LightRFAttrSet); //设置模态框
                //功放控制模式
                $("#AmpControlMode").html(getLoop(data.AmpControlMode));
                $("#setAmpControlMode").attr('data-value', data.AmpControlMode);
                //DA设置值
                $("#DASet").html(data.DASet);
                $("#setDASet").attr('data-value', data.DASet); //设置模态框
                //驻波比保护门限
                $("#AmpVSWRThreshold").html(data.AmpVSWRThreshold);
                $("#setAmpVSWRThreshold").attr('data-value', data.AmpVSWRThreshold); //设置模态框
                //功率保护门限
                $("#AmpPowerThreshold").html(data.AmpPowerThreshold + 'W');
                $("#setAmpPowerThreshold").attr('data-value', data.AmpPowerThreshold); //设置模态框
                //DA保护门限
                $("#AmpDACThreshold").html(data.AmpDACThreshold);
                $("#setAmpDACThreshold").attr('data-value', data.AmpDACThreshold); //设置模态框
                //功放温度保护门限
                $("#AmpTMPThreshold").html(data.AmpTMPThreshold + '℃');
                $("#setAmpTMPThreshold").attr('data-value', data.AmpTMPThreshold); //设置模态框


                $("#LightRecvPower").html(data.LightRecvPower + 'dbm');
                $("#LightInAlarm").html(getAlarm(data.LightInAlarm));
                $("#LightCommSta").html(getStatus(data.LightCommSta));
                $("#LightRFAttr").html(data.LightRFAttr + 'db');
                $("#AmpOutControlDAC").html(data.AmpOutControlDAC);
                $("#AmpRefPower").html(data.AmpRefPower + 'W');
                $("#AmpFwdPower").html(data.AmpFwdPower + 'W');
                $("#AmpOutputVoltage").html(data.AmpOutputVoltage + 'V');
                $("#AmpOutputCurrent").html(data.AmpOutputCurrent + 'A');
                $("#AmpTemperature").html(data.AmpTemperature + '℃');
                $("#AmpVSWR").html(data.AmpVSWR);
                $("#LoopStatus").html(getLoopStatus(data.LoopStatus));
                $("#AmpVSWRWarning").html(getAlarm(data.AmpVSWRWarning));
                $("#AmpLastProVSWR").html(data.AmpLastProVSWR);
                $("#AmpCVSWRPro").html(data.AmpCVSWRPro);
                $("#AmpCVSWRProRec").html(getTimes(data.AmpCVSWRProRec));
                $("#AmpPowerWarning").html(getAlarm(data.AmpPowerWarning));
                $("#AmpCPowerPro").html(data.AmpCPowerPro);
                $("#AmpCPowerProRec").html(getTimes(data.AmpCPowerProRec));
                $("#AmpDACWarning").html(getAlarm(data.AmpDACWarning));
                $("#AmpCDACPro").html(data.AmpCDACPro);
                $("#AmpCDACProRec").html(getTimes(data.AmpCDACProRec));
                $("#AmpTMPWarning").html(getAlarm(data.AmpTMPWarning));
                $("#AmpCTMPPro").html(data.AmpCTMPPro);
                $("#AmpCRecTime").html(data.AmpCRecTime);

            } else {
                failure(res.data.msg);
                clearInterval(intervalTime);
            }
        },
        error: function(XHR) {
            error(XHR);
        }
    });
}

/**
 * 获取网络配置
 * @return {[type]} [description]
 */
function getNetWorkData() {
    $.ajax({
        url: geturl('NETWORK_CGI.cgi/NETWORKDATA'),
        type: 'GET',
        beforeSend: function(xhr) {
            // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
            xhr.setRequestHeader("Content-Type", "application/json")
        },
        success: function(res) {
            if (res.success == "true") {
                var data = res.data;
                //网络配置
                $("#IsDHCP").html(isDHCP(data.IsDHCP));
                $("#setDHCP").attr('data-value', data.IsDHCP);

                $("#IPAddress").html(data.IPAddress);
                $("#setIPAddress").attr('data-value', data.IPAddress); //设置模态框

                $("#Netmask").html(data.Netmask);
                $("#setNetmask").attr('data-value', data.Netmask); //设置模态框


                $("#Gateway").html(data.Gateway);
                $("#setGateway").attr('data-value', data.Gateway); //设置模态框


                $("#MACAddress").html(data.MACAddress);
                $("#netWorkDataTime").html(res.DataTime);
            } else {
                failure(res.data.msg);
                clearInterval(intervalTime);
            }
        },
        error: function(XHR) {
            error(XHR);
        }
    });
}
/*--------------------获取直放站数据end--------------------------*/

/*--------------------设置直放站数据 start------------------------------*/
//射频开关设置
$("#setSwitch").click(function() {
    var $this = $(this);
    if (userToken != '') {
        if ($this.hasClass('switch--open')) {
            swal({
                title: "确认将开关设置为关？",
                text: "",
                type: "warning",
                showCancelButton: true,
                closeOnConfirm: false,
                confirmButtonText: "确定",
                confirmButtonColor: "#ec6c62"
            }, function() {
                var data0 = {
                    token: window.localStorage.getItem('user_token'),
                    time_stamp: window.localStorage.getItem('time_stamp'),
                    data: {
                        RFSwitch: 0
                    }
                };
                data0 = JSON.stringify(data0);
                setData('OHOPT_CGI.cgi/OHOPTDATA', data0, '操作成功！');
                $this.removeClass('switch--open').addClass('switch--close');
            });
        } else {
            swal({
                title: "确认将开关设置为开？",
                text: "",
                type: "warning",
                showCancelButton: true,
                closeOnConfirm: false,
                confirmButtonText: "确定",
                confirmButtonColor: "#ec6c62"
            }, function() {
                var data0 = {
                    token: window.localStorage.getItem('user_token'),
                    time_stamp: window.localStorage.getItem('time_stamp'),
                    data: {
                        RFSwitch: 1
                    }
                };
                data0 = JSON.stringify(data0);
                setData('OHOPT_CGI.cgi/OHOPTDATA', data0, '操作成功！');
                $this.removeClass('switch--close').addClass('switch--open');
            });
        }
    } else {
        window.swal({
            title: '您未登录，请登录后进行设置！',
            text: '',
            type: 'warning',
            timer: 2000,
            showConfirmButton: false
        });
    }
});


//重启设置
$("#setSysReset").click(function() {
    if (userToken != '') {
        swal({
            title: "确认要进行重启？",
            text: "",
            type: "warning",
            showCancelButton: true,
            closeOnConfirm: false,
            confirmButtonText: "确定",
            confirmButtonColor: "#ec6c62"
        }, function() {
            var data0 = {
                token: window.localStorage.getItem('user_token'),
                time_stamp: window.localStorage.getItem('time_stamp'),
                data: {
                    SysReset: 1
                }
            };
            data0 = JSON.stringify(data0);
            setData('OHOPT_CGI.cgi/OHOPTDATA', data0, '操作成功！');
            swal.close();
        });
    } else {
        window.swal({
            title: '您未登录，请登录后进行设置！',
            text: '',
            type: 'warning',
            timer: 2000,
            showConfirmButton: false
        });
    }
});



//复位设置
$("#setReset").click(function() {
    var data0 = {
        token: userToken,
        time_stamp: timeStamp,
        data: {
            SoftReset: 1
        }
    };
    data0 = JSON.stringify(data0);
    setData('OHOPT_CGI.cgi/OHOPTDATA', data0, '复位成功！');
});

//写入FLASH设置
$("#setFlashWr").click(function() {
    var data0 = {
        token: userToken,
        time_stamp: timeStamp,
        data: {
            FLASHWR: 1
        }
    };
    data0 = JSON.stringify(data0);
    setData('OHOPT_CGI.cgi/OHOPTDATA', data0, '保存成功！');
});

//功放控制模式
function AmpControlModeSetCtrl(obj) {
    var thisObj = $(obj);
    var $val = thisObj.parent().prev().find('input[name=AmpControlMode]:checked').val();
    var data0 = {
        token: userToken,
        time_stamp: timeStamp,
        data: {
            AmpControlMode: $val
        }
    };
    data0 = JSON.stringify(data0);
    setData('OHOPT_CGI.cgi/OHOPTDATA', data0, '操作成功！', $("#AmpControlModal"));
}

//设置是否自动获取
function setIsDHCP(obj) {
    var thisObj = $(obj);
    var $val = thisObj.parent().prev().find('input[name=IsDHCPOption]:checked').val();
    var data0 = {
        token: userToken,
        time_stamp: timeStamp,
        data: {
            IsDHCP: $val
        }
    };
    data0 = JSON.stringify(data0);
    setData('NETWORK_CGI.cgi/NETWORKDATA', data0, '操作成功！', $("#DHCPModal"));
}

//其他模态框数值设置
function query(obj) {
    var thisObj = $(obj);
    var $val = thisObj.parent().prev().find('.setInput').val();
    var min = thisObj.parent().prev().find('.setInput').attr('min'),
        max = thisObj.parent().prev().find('.setInput').attr('max');
    var key = thisObj.parent().prev().find('.setInput').attr('data-key');
    var url = '';
    if (key == 'IPAddress' || key == 'Netmask' || key == 'Gateway') {
        url = 'NETWORK_CGI.cgi/NETWORKDATA';
    } else {
        url = 'OHOPT_CGI.cgi/OHOPTDATA';
    }
    var data0 = {
        token: userToken,
        time_stamp: timeStamp
    };
    var dataKey = {
        key: $val
    };

    // 复制原来的值
    dataKey[key] = dataKey['key'];
    // 删除原来的键
    delete dataKey['key'];
    data0.data = dataKey;
    data0 = JSON.stringify(data0);

    if ($val != '') {
        if (Number($val) < Number(min) || Number($val) > Number(max)) {
            swal({
                title: '数值范围有误，请重新输入',
                type: 'error',
                timer: 2000,
                allowOutsideClick: false,
                allowEscapeKey: false,
                showConfirmButton: false
            });
            thisObj.parent().prev().find('.setInput').val('');
            return;
        } else {
            setData(url, data0, '操作成功！', $("#myModal"));
        }
    }
}


/*MCU升级*/
$("#setUpgrade").click(function(){
     var data0 = {
        token: userToken,
        time_stamp: timeStamp,
        data: {
            MCU_OTA: 1
        }
    };
    data0 = JSON.stringify(data0);
    setData('OHOPT_CGI.cgi/OHOPTDATA', data0, '操作成功！');
});


/**
 * @param url  请求地址
 * @param data0 参数
 * @param tips 成功提示信息
 * @param ele 模态框
 */
function setData(url, data0, tips, ele) {
    if (userToken != '') {
        $.ajax({
            url: geturl(url),
            type: 'POST',
            data: data0,
            beforeSend: function(xhr) {
                // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
                xhr.setRequestHeader("Content-Type", "application/json")
            },
            success: function(res) {
                // var ObjData = JSON.parse(res);
                if (res.success == "true") {
                    swal({
                        title: tips,
                        type: "success",
                        timer: 2000,
                        showConfirmButton: false
                    });
                    //重新查询
                    setTimeout(function() {
                        getOHOPTData();
                        getNetWorkData();
                    }, 2000);
                    //如果有模态框-hide
                    if (ele) { ele.modal('hide'); }

                } else {
                    failure(res.data.msg);
                    //如果有模态框-hide
                    if (ele) { ele.modal('hide'); }
                }
            },
            error: function(XHR) {
                error(XHR);
                if (ele) { ele.modal('hide'); }
            }
        });
    } else {
        window.swal({
            title: '您未登录，请登录后进行设置！',
            text: '',
            type: 'warning',
            timer: 2000,
            showConfirmButton: false
        });
    }

}

/*--------------------设置直放站数据 end------------------------------*/

//获取相关状态值
function getStatus(param) {
    if (param == 1) { return '<span class="normal">正常</span>' } else if (param == 0) { return '<span class="abnormal">异常</span>' } else {
        return '未知'
    }
}

//获取开关状态
function getOpen(param) {
    if (param == 0) { return '关' } else if (param == 1) { return '开' } else {
        return '未知'
    }
}

//获取环路模式--功放控制模式
function getLoop(param) {
    if (param == 0) { return '设置模式' } else if (param == 1) { return '跟踪模式' } else {
        return '未知';
    }
}
//环路状态
function getLoopStatus(param) {
    if (param == 0) { return '正常开' } else if (param == 1) { return '正常关' } else if (param == 2) { return '保护降' } else if (param == 3) {
        return '保护限'
    } else if (param == 4) {
        return '保护关'
    } else {
        return '未知';
    }
}

//获取告警状态
function getAlarm(param) {
    if (param == 1) { return '<span class="normal">正常</span>' } else if (param == 0) { return '<span class="abnormal">告警</span>' } else {
        return '未知'
    }
}

//获取自恢复次数
function getTimes(param) {
    param = Number(param);
    if (param < 4) { return param; } else if (param == 4) { return '不再恢复' } else {
        return '未知';
    }
}

//是否动态获取
function isDHCP(param) {
    if (param == 0) { return '静态设置' } else if (param == 1) { return '动态获取' } else {
        return '未知';
    }
}